import { login, getUser } from '@/api/user.js';
import { setItem, getItem, removeAllItem } from '@/utils/storage';
import { setTimeStamp } from '@/utils/auth';
import { ElMessage } from 'element-plus';

import router from '@/router/index.js';
import md5 from 'md5';
export default {
  namespaced: true,
  state: () => ({
    token: getItem('token') || '',
    userInfo: {},
  }),
  mutations: {
    setToken(state, token) {
      state.token = token;
      setItem('token', token);
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
  },
  actions: {
    login(context, userInfo) {
      const { account, password } = userInfo;
      return new Promise((resolve, reject) => {
        login({
          account,
          password,
        })
          .then((res) => {
            // 登录成功，设置token
            this.commit('user/setToken', res.data.token);
            ElMessage.success(res.data.message);
            // 记录时间戳
            router.push('/');
            setTimeStamp();
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    getUserInfo(context) {
      return new Promise((resolve, reject) => {
        getUser()
          .then((res) => {
            this.commit('user/setUserInfo', res);
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    logout() {
      this.commit('user/setToken', '');
      this.commit('user/setUserInfo', {});
      removeAllItem();
      router.push('/login');
    },
  },
};
